#!/usr/bin/env python
import os,sys,re
import glob
from pathlib import Path

def get_KK_input(sample):
    KK_in=glob.glob(f'{sample}')
    if KK_in:
        KK_size=os.path.getsize(KK_in[0])
        if int(KK_size)>10:
            return True
    else:
        return False


def run(sample):
    workdir=str(Path(sample).parent)+'/'
    prefix=str(Path(sample).name).strip('.removepla.fasta')
    cmd=f'/data/softwares/newalign/bwa-mem2-2.1_x64-linux/bwa-mem2 mem -t 10 /data/softwares/newalign/bwa-mem2-2.1_x64-linux/plasmid/plasmid.fa   {workdir}/{prefix}.remained.fasta  \
| samtools fastq -f 4 --threads 18 - | seqkit fq2fa -j 18 -w 0 -o {sample} - '    

    os.system(f"cd {workdir} &&  {cmd}")

flags=0

n=0

while 1:
    
    if flags==0:
        if get_KK_input(sys.argv[1]):
            flags=1
            print(f'run task successfully ! ')
        else:
            n+=1
            print(f'rerun task for {n} times')
            run(sys.argv[1])
            if n==4:
                sys.exit()
    if flags==1:
        break

